package com.woniuxy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.dto.goodsGeneralAndSmallAndBrand.*;
import com.woniuxy.entity.GoodsGeneral;
import com.woniuxy.entity.GoodsSmall;
import com.woniuxy.entity.GoodsSmaller;
import com.woniuxy.enums.CodeEnum;
import com.woniuxy.exception.GoodsGeneralException;
import com.woniuxy.exception.GoodsSmallException;
import com.woniuxy.mapper.GoodsSmallMapper;
import com.woniuxy.param.goodsGeneralAndSmallAndBrand.AddGoodsSmallParam;
import com.woniuxy.param.goodsGeneralAndSmallAndBrand.DeleteSmallParam;
import com.woniuxy.param.goodsGeneralAndSmallAndBrand.ListGoodsSmallParam;
import com.woniuxy.param.goodsGeneralAndSmallAndBrand.UpdateGoodsSmallParam;
import com.woniuxy.service.GoodsGeneralService;
import com.woniuxy.service.GoodsSmallService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.util.WoniuBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品小类 服务实现类
 * </p>
 *
 * @author zcx, ftl, gr, rhs
 * @since 2021-12-31
 * 商品小类信息管理服务实现类
 */
@Service
public class GoodsSmallServiceImpl extends ServiceImpl<GoodsSmallMapper, GoodsSmall> implements GoodsSmallService {

    @Resource
    private GoodsGeneralService goodsGeneralService;
    //修改做redis保存
    @Resource
    private RedisTemplate<String, List<GoodsSmallDto>> rt;

    /**
     * 新增小类信息
     *
     * @param addGoodsSmallParam 前端发送的新增小类的信息
     * @return 返回给前端的小类信息
     */
    @ExceptionHandler(Exception.class)
    @Override
    public GoodsSmallDto saveSmallInfo(AddGoodsSmallParam addGoodsSmallParam) {

        GoodsSmall smallByName = getOne(new QueryWrapper<GoodsSmall>().eq("goods_small_name", addGoodsSmallParam.getGoodsSmallName()));

//        if (null != smallByName) throw new GoodsSmallException("小类信息已存在，新增失败",1050);
        if (null != smallByName)
            throw new GoodsSmallException(CodeEnum.SMALL_ADD_FAIL.getMessage(), CodeEnum.SMALL_ADD_FAIL.getCode());
        //需要根据大类id查出大类名字 保存起来 前段没做这方面处理 只传过来了大类id
        GoodsGeneral generalDB = goodsGeneralService.getById(addGoodsSmallParam.getGoodsGeneralId());

        //满足新增条件 开始新增
        GoodsSmall goodsSmall = new GoodsSmall();
        BeanUtils.copyProperties(addGoodsSmallParam, goodsSmall);
        goodsSmall.setGoodsGeneralName(generalDB.getGoodsGeneralName());//添加大类名字给小类
        save(goodsSmall);
        List<GoodsSmallDto> range = rt.opsForValue().get("pawn:goods:small:" + goodsSmall.getGoodsGeneralId());
        if (null == range || range.size() <= 0) {
        } else {
            rt.delete("pawn:goods:small:" + goodsSmall.getGoodsGeneralId());
        }
        GoodsSmallDto goodsSmallDto = new GoodsSmallDto();
        BeanUtils.copyProperties(goodsSmall, goodsSmallDto);

        return goodsSmallDto;
    }

    /**
     * 分页+模糊查询+大类名称查询小类信息
     *
     * @param limitParam 分页查询大类信息的参数
     * @return 分页查询返回给前端的数据
     */
    @Override
    public PageGoodsSmallDto pageFind(ListGoodsSmallParam limitParam) {
        QueryWrapper<GoodsSmall> queryWrapper = new QueryWrapper<>();
        //0表示未逻辑删除，才可以查询得到
        queryWrapper.eq("goods_small_status", 0);
        if (null != limitParam.getKeyword()) {
            //模糊查询的条件应该是一个组合条件 即sql要加括号！
            queryWrapper.and(qw -> {
                qw.like("goods_small_name", limitParam.getKeyword())
                        .or()
                        .like("goods_general_name", limitParam.getKeyword());
            });
        }
        //加个按照主键降序的条件
        queryWrapper.orderByDesc("goods_small_id");
        IPage<GoodsSmall> iPage = page(new Page<>(limitParam.getIndexPage(), limitParam.getPageSize()), queryWrapper);
        PageGoodsSmallDto pageGoodsSmallDto = new PageGoodsSmallDto();
        //塞入当前页
        pageGoodsSmallDto.setIndexPage(iPage.getCurrent());
        //塞入总条数
        pageGoodsSmallDto.setTotal(iPage.getTotal());
        //塞入数据
        pageGoodsSmallDto.setGoodsSmallDtos(WoniuBeanUtils.copyList(iPage.getRecords(), GoodsSmallDto.class));
        return pageGoodsSmallDto;
    }


    /**
     * 修改小类信息
     *
     * @param updateGoodsSmallParam
     * @return
     */
    @ExceptionHandler(Exception.class)
    @Override
    public UpdateGoodsSmallDto updateSmallInfo(UpdateGoodsSmallParam updateGoodsSmallParam) {
        //先根据id查询 返回小类对象
        GoodsSmall smallDB = getById(updateGoodsSmallParam.getGoodsSmallId());
        //在判断该对象是否满足修改要求
        if (smallDB.getGoodsSmallStatus() == 1)
//            throw new GoodsSmallException("该小类信息无法修改", 1051);
            throw new GoodsSmallException(CodeEnum.SMALL_UPDATE_NOWAY.getMessage(), CodeEnum.SMALL_UPDATE_NOWAY.getCode());
        BeanUtils.copyProperties(updateGoodsSmallParam, smallDB);
        if (updateById(smallDB)) {
            List<GoodsSmallDto> range = rt.opsForValue().get("pawn:goods:small:" + smallDB.getGoodsGeneralId());
            if (null == range || range.size() <= 0) {
            } else {
                rt.delete("pawn:goods:small:" + smallDB.getGoodsGeneralId());
            }

            return WoniuBeanUtils.copyObject(smallDB, UpdateGoodsSmallDto.class);
        }
//        throw new GoodsSmallException("修改失败", 1025);
        throw new GoodsSmallException(CodeEnum.SMALL_UPDATE_FAIL.getMessage(), CodeEnum.SMALL_UPDATE_FAIL.getCode());
    }


    /**
     * 批量删除小类信息
     *
     * @param deleteSmallParam
     * @return 删除成功就返回true
     */
    @ExceptionHandler(Exception.class)
    @Override
    public Boolean deleteGoodsSmall(DeleteSmallParam deleteSmallParam) {

        List<GoodsSmall> smalls = list(new QueryWrapper<GoodsSmall>().in("goods_small_id", deleteSmallParam.getGoodsSmallIds()));
//        if (null == smalls || smalls.size() <= 0) throw new GoodsSmallException("小类信息不存在", 1051);
        if (null == smalls || smalls.size() <= 0)
            throw new GoodsSmallException(CodeEnum.SMALL_INFO_NULL.getMessage(), CodeEnum.SMALL_INFO_NULL.getCode());
        //过滤掉不符合删除条件的数据
        List<GoodsSmall> collect = smalls.stream().filter(small -> {
            Boolean flag = !(small.getGoodsSmallStatus() == 1);
            //逻辑删除
            if (flag) small.setGoodsSmallStatus(1);
            return flag;
        }).collect(Collectors.toList());//将符合删除条件的数据添加到新集合内
//        if (collect.size() != smalls.size()) throw new GoodsSmallException("有小类不满足删除条件", 1011);
        if (collect.size() != smalls.size())
            throw new GoodsSmallException(CodeEnum.SMALL_DELETE_NOWAY.getMessage(), CodeEnum.SMALL_DELETE_NOWAY.getCode());
        for (GoodsSmall goodsSmall : collect) {
            List<GoodsSmallDto> range = rt.opsForValue().get("pawn:goods:small:" + goodsSmall.getGoodsGeneralId());
            if (null == range || range.size() <= 0) {
            } else {
                rt.delete("pawn:goods:small:" + goodsSmall.getGoodsGeneralId());
            }

        }

        return updateBatchById(collect);
    }


    @Override
    public List<GoodsSmallDto> listGoodsSmallDto(Integer goodsGeneralId) {
        List<GoodsSmallDto> range = rt.opsForValue().get("pawn:goods:small:" + goodsGeneralId);
        if (null == range || range.size() <= 0) {
            QueryWrapper<GoodsSmall> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_small_status", 0).eq("goods_general_id", goodsGeneralId);
            List<GoodsSmall> list = list(queryWrapper);
            List<GoodsSmallDto> dtos = WoniuBeanUtils.copyList(list, GoodsSmallDto.class);
            rt.opsForValue().set("pawn:goods:small:" + goodsGeneralId, dtos);
            rt.expire("pawn:goods:small:" + goodsGeneralId, 30, TimeUnit.MINUTES);
            return dtos;
        } else {
            return range;
        }

    }

    @Override
    public List<GoodsSmallDto> listGoodsSmall() {
        QueryWrapper<GoodsSmall> queryWrapper = new QueryWrapper<>();
        //0表示未逻辑删除，才可以查询得到
        queryWrapper.eq("goods_small_status", 0);

        return WoniuBeanUtils.copyList(list(queryWrapper), GoodsSmallDto.class);
    }




}
